package com.k.kpp.util.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.util.Date;

/**
 * 1.全局处理
 * 1.1 添加 自定义序列化类上@JsonComponent 注解
 *     @JsonComponent
 *     public class XXSerializer extends JsonSerializer<Date> {}
 * 1.2 Bean 属性不需要添加任何注解
 *     private Date createTime;
 *
 * 2.局部属性处理
 * 2.1 删除 自定义序列化类上@JsonComponent 注解
 *     public class XXSerializer extends JsonSerializer<Date> {}
 * 2.2 Bean 中属性添加
 *     @JsonSerialize(using = DateToLongSerializer.class)
 *     private Date createTime;</code>
 *
 * @author k
 */
//@JsonComponent  会影响全局的 时间
public class StringToDateDeserializer  extends JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        String dateStr = jsonParser.getCurrentName();
        if(dateStr!=null && dateStr.trim().length()>0){
            long dateLong = Long.parseLong(dateStr);
            Date d = new Date(dateLong);
            return d;
        }
        return null;
    }
}
